{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import ast\n",
    "\n",
    "\n",
    "import sys\n",
    "sys.path.append(r'D:\\codeproject\\data-process')\n",
    "import pyhrv.nonlinear as nl  # 导入pyHRV的非线性分析模块\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "#读取stage文件将个人的信息匹配到记录中\n",
    "all_stages_path_path = r'D:\\学习&科研\\华为手表项目\\华为数据\\base-data\\juypterall_stages_df.csv'\n",
    "all_stages_path = pd.read_csv(all_stages_path_path)\n",
    "info = pd.read_csv(r'D:\\学习&科研\\华为手表项目\\华为数据\\base-data\\受试者信息统计表utf8.csv')\n",
    "# 替换性别信息\n",
    "info['sex'] = info['sex'].replace({'男': 1, '女': 0})\n",
    "\n",
    "# 提取 all_stages_path 中 number 的前四位\n",
    "all_stages_path['id'] = all_stages_path['number'].astype(str).str[:4]\n",
    "\n",
    "# 确保 info 中的 id 列为字符串类型\n",
    "info['id'] = info['id'].astype(str)\n",
    "\n",
    "# 使用 merge 函数将 info 的所有列填充到 all_stages_path 中\n",
    "all_stages_path = all_stages_path.merge(info, on='id', how='left')\n",
    "\n",
    "\n",
    "all_stages_path.to_csv(r'D:\\学习&科研\\华为手表项目\\华为数据\\base-data\\全阶段+info.csv', index=False)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "#读取stage文件，计算根据hr和rr计算出应有的统计信息\n",
    "# 读取 CSV 文件\n",
    "all_stages_path=r'D:\\学习&科研\\华为手表项目\\华为数据\\base-data\\全阶段+info.csv'\n",
    "all_stages_df=pd.read_csv(all_stages_path)\n",
    "\n",
    "# #增加hr和rr的统计信息\n",
    "# # 将 polar_hr 和 polar_rr 列转换为列表\n",
    "# all_stages_df['polar_hr'] = all_stages_df['polar_hr'].apply(ast.literal_eval)\n",
    "# all_stages_df['polar_rr'] = all_stages_df['polar_rr'].apply(ast.literal_eval)\n",
    "\n",
    "\n",
    "# # 定义函数来计算统计特征\n",
    "def calculate_statistics(lst):\n",
    "    return {\n",
    "        'mean': np.mean(lst),\n",
    "        'std': np.std(lst),\n",
    "        'min': np.min(lst),\n",
    "        'max': np.max(lst),\n",
    "        'median': np.median(lst),\n",
    "        'q1': np.percentile(lst, 25),\n",
    "        'q3': np.percentile(lst, 75),\n",
    "        'range': np.max(lst) - np.min(lst),\n",
    "        'skewness': pd.Series(lst).skew(),\n",
    "        'kurtosis': pd.Series(lst).kurtosis()\n",
    "    }\n",
    "\n",
    "# # 计算 polar_hr 的统计特征\n",
    "# hr_stats = all_stages_path['polar_hr'].apply(calculate_statistics).apply(pd.Series)\n",
    "# all_stages_path = pd.concat([all_stages_path, hr_stats.add_prefix('polar_hr_')], axis=1)\n",
    "\n",
    "# # 计算 polar_rr 的统计特征\n",
    "# rr_stats = all_stages_path['polar_rr'].apply(calculate_statistics).apply(pd.Series)\n",
    "# all_stages_path = pd.concat([all_stages_path, rr_stats.add_prefix('polar_rr_')], axis=1)\n",
    "# #polar_rr为列表数据，通过函数计算得到指标，加入该行\n",
    "#polar_rr为列表数据，通过函数计算得到指标，加入该行\n",
    "# 定义 calculate_sd1_sd2 函数\n",
    "all_stages_df['polar_rr'] = all_stages_df['polar_rr'].apply(lambda x: eval(x) if isinstance(x, str) else x)\n",
    "\n",
    "# 定义 calculate_sd1_sd2 函数\n",
    "def calculate_sd1_sd2(rr_intervals):\n",
    "    if not isinstance(rr_intervals, (list, np.ndarray)) or len(rr_intervals) < 2:\n",
    "        return np.nan, np.nan  # 如果数据不符合要求，返回 NaN\n",
    "    \n",
    "    rr_diff = np.diff(rr_intervals)\n",
    "    rr_diff_n = rr_diff[:-1]\n",
    "    rr_diff_np1 = rr_diff[1:]\n",
    "\n",
    "    SD1 = np.sqrt(np.std(rr_diff_n - rr_diff_np1, ddof=1) / 2)\n",
    "    SD2 = np.sqrt(np.std(rr_diff_n + rr_diff_np1, ddof=1) / 2)\n",
    "\n",
    "    return SD1, SD2\n",
    "def calculate_sdnn_rmssd(rr_intervals):\n",
    "    try:\n",
    "        SDNN = np.std(rr_intervals, ddof=1)  # SDNN的计算\n",
    "        RMSSD = np.sqrt(np.mean(np.square(np.diff(rr_intervals))))  # RMSSD的计算\n",
    "        return SDNN, RMSSD\n",
    "    except:\n",
    "        return None, None\n",
    "def calculate_cv(rr_intervals):\n",
    "    mean_rr = np.mean(rr_intervals)\n",
    "    std_rr = np.std(rr_intervals, ddof=1)\n",
    "    cv = std_rr / mean_rr if mean_rr != 0 else 0\n",
    "    mean_hr = 60000 / mean_rr\n",
    "    return cv, mean_hr\n",
    "\n",
    "# def calculate_dfa(rr_intervals):\n",
    "#     # 使用pyHRV计算DFA\n",
    "#     dfa_result = nl.dfa(rr_intervals ,show=False)\n",
    "#     alpha1 = dfa_result['dfa_alpha1']  # DFA的短期指数\n",
    "#     alpha2 = dfa_result['dfa_alpha2']  # DFA的长期指数\n",
    "#     return alpha1, alpha2\n",
    "# 应用 calculate_sd1_sd2 函数并提取 SD1 和 SD2\n",
    "# all_stages_df[['SD1', 'SD2']] = all_stages_df['polar_rr'].apply(lambda x: pd.Series(calculate_sd1_sd2(x)))\n",
    "\n",
    "all_stages_df[['SDNN', 'RMSSD']] = all_stages_df['polar_rr'].apply(lambda x: pd.Series(calculate_sdnn_rmssd(x)))\n",
    "# all_stages_df[['CV', 'Mean_HR']] = all_stages_df['polar_rr'].apply(lambda x: pd.Series(calculate_cv(x)))\n",
    "# all_stages_df[['alpha1', 'alpha2']] = all_stages_df['polar_rr'].apply(lambda x: pd.Series(calculate_dfa(x)))\n",
    "#指定某几列数据为数字类型\n",
    "# all_stages_df[['SD1', 'SD2','SDNN', 'RMSSD','CV', 'Mean_HR']] = all_stages_df[['SD1', 'SD2','SDNN', 'RMSSD','CV', 'Mean_HR']].astype(float)  # 或 int\n",
    "all_stages_df.to_csv(r'D:\\学习&科研\\华为手表项目\\华为数据\\base-data\\全阶段+info+hrv.csv',index=False)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "MLandDL",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.20"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
